package com.cloud.security.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloud.platform.Constants;
import com.cloud.platform.IDao;
import com.cloud.platform.StringUtil;
import com.cloud.security.model.User;

@Service
public class UserService {

	@Autowired
	private IDao dao;
	
	/**
	 * get user by user id
	 * 
	 * @param userId
	 * @return
	 */
	public User getUserById(String userId) {
		
		if(StringUtil.isNullOrEmpty(userId)) {
			return new User();
		}
		
		return (User) dao.getObject(User.class, userId);
	}
	
	/**
	 * search type users
	 * 
	 * @param type
	 * @return
	 */
	public List<User> searchUsers(int type) {
		String hql = "";
		
		// select all users
		if(type == Constants.USER_TYPE_ALL) {
			hql = "from User order by username";
			return dao.getAllByHql(hql);
		}
		// select type users
		else {
			hql = "from User where type = ? order by username";
			return dao.getAllByHql(hql, type);
		}
	}
	
	/**
	 * save user
	 * 
	 * @param username
	 * @param password
	 * @param email
	 * @param address
	 */
	public void saveUser(int type, String username, String password, String email, String address) {
		
		User u = new User();
		
		u.setId(Constants.getID());
		u.setType(type);
		u.setUsername(username);
		u.setPassword(password);
		u.setEmail(email);
		u.setAddress(address);
		
		dao.saveObject(u);
		
		// reset user cache
		Constants.userIdNameMap = null;
		Constants.userNameIdMap = null;
	}
}
